var CLIENT_ID = '188398434606-954vkmtlr837crsicvpujkhso7g8g06g.apps.googleusercontent.com';
var SCOPES = 'https://www.googleapis.com/auth/drive';
var File_ID_COOKIE = 'FileIDCookie';
var STRUCT_GUID = 'D85F9033-70B0-4E2C-898A-899834E1C033';
var struct = { groups: {} }, session = {};

$(function ()
{
    $("#ImportFromGoogleReaderDialog").dialog(
            {
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    'Yes': function ()
                    {
                        this.dialogResult = 1;
                        $(this).dialog("close");
                    },
                    'No': function ()
                    {
                        this.dialogResult = 0;
                        $(this).dialog("close");
                    }
                }
            });
});

function checkAuth()
{
    gapi.auth.authorize({ 'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false }, handleAuthResult);
}

function handleAuthResult(authResult)
{
    if (authResult && !authResult.error)
    {
        init();
    }
    else
    {
        alert('Google api authorization error: Popup blocker active? If yes disable popup blocker and refresh page.');
    }
}

function init()
{
    if ($.cookie(File_ID_COOKIE))
    {
        fetch_data($.cookie(File_ID_COOKIE), function (success)
        {
            if (success)
            {
                build_navigation();
                init_completion();
            }
            else
            {
                $.removeCookie(File_ID_COOKIE, { path: '/' });
                init();
            }
        });
        return;
    }

    var request = gapi.client.request({
        'path': 'drive/v2/files',
        'method': 'GET',
        'params':
        {
            "q": "title = '" + STRUCT_GUID + "'"
        }
    });
    request.execute(function (response)
    {
        if (response.items.length == 1)
            fetch_data(response.items[0].id);
        else
        {
            $("#ImportFromGoogleReaderDialog").dialog("open").on('dialogclose',
                function (event, ui)
                {
                    struct.groups['Miscellaneous'] = { s: {} };
                    if (this.dialogResult == 1)
                    {
                        var xml = $.parseXML($('#importXml').val());
                        if (xml)
                            google_reader_import($(xml));
                        else
                            alert('XML import failed!');
                    }
                    store_data();
                    build_navigation();
                    init_completion();
                });
        }
    });
}

function fetch_data(file_id, callback)
{
    gapi.client.request({
        'path': '/drive/v2/files/' + file_id,
        'method': 'GET',
        callback: function (theResponseJS, theResponseTXT)
        {
            var myToken = gapi.auth.getToken();
            var myXHR = new XMLHttpRequest();
            myXHR.open('GET', theResponseJS.downloadUrl, true);
            myXHR.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
            myXHR.onreadystatechange = function (theProgressEvent)
            {
                if (myXHR.readyState == 4)
                {
                    if (myXHR.status == 200)
                    {
                        struct = JSON.parse(myXHR.response);
                        $.cookie(File_ID_COOKIE, file_id, { expires: 7 * 52, path: '/' });
                        if ($.isFunction(callback)) callback(true);
                    }
                    else if ($.isFunction(callback)) callback(false);
                }
            }
            myXHR.send();
        }
    });
}

function store_data(file_id, callback)
{
    var file_content = JSON.stringify(struct);
    if (!file_id)
    {
        insertFile(STRUCT_GUID, file_content, function (resp)
        {
            $.cookie(File_ID_COOKIE, resp.id, { expires: 7 * 52, path: '/' });
            if ($.isFunction(callback)) callback(true);
        });
    }
    else
    {
        updateFile(file_id, file_content, function ()
        {
            if ($.isFunction(callback)) callback(true);
        });
    }
}

function store_session()
{
    var file_content = JSON.stringify(session);
}

function init_completion()
{
    $('#accordion').accordion({ heightStyle: "content" });
    $('.cog').click(function ()
    {
        return false;
    }).toolbar({
        content: '#user-options',
        position: 'bottom',
        hideOnClick: true
    });
}

function google_reader_import(xml)
{
    var body = xml.find('body');
    var outlines = body.find('outline');
    var addSub = function (groupName, xml)
    {
        var group = struct.groups[groupName];
        if (!group)
        {
            group = (struct.groups[groupName] = { s: {} });
        }
        group.s[outline.attr('title')] =
            {
                xmlUrl: outline.attr('xmlUrl'),
                htmlUrl: outline.attr('htmlUrl')
            };
    };
    for (var i = 0; i < outlines.length; i++)
    {
        var outline = $(outlines[i]);
        var type = outline.attr('type');
        if (type === 'rss')
        {
            var parent = outline.parent();
            addSub(parent.attr('title') ? parent.attr('title') : 'Miscellaneous', outline);
        }
    }
}

function build_navigation()
{
    for (var group in struct.groups)
    {
        var html = '<h3>' + group + '<img src="./img/icon-cog-small.png" class="cog" /></h3><div>';
        for (var sub in struct.groups[group].s)
        {
            var title = sub.length > 24 ? sub.substring(0, 24) + '...' : sub;
            html += '<div class="s_div"><img src="img/rss.png" class="rssicon" /><span>' + title + '</span></div>';
        }
        $('#accordion').append(html + '</div>');
    }
}

function insertFile(fileName, fileData, callback)
{
    var boundary = '-------314159265358979323846';
    var delimiter = "\r\n--" + boundary + "\r\n";
    var close_delim = "\r\n--" + boundary + "--";

    var metadata = {
        'title': fileName,
        'mimeType': 'application/json'
    };
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        delimiter +
        'Content-Type: application/json\r\n' +
        'Content-Transfer-Encoding: base64\r\n' +
        '\r\n' + btoa(fileData) + close_delim;

    var request = gapi.client.request({
        'path': '/upload/drive/v2/files',
        'method': 'POST',
        'params': { 'uploadType': 'multipart' },
        'headers': {
            'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody
    });
    request.execute(callback);
}

function updateFile(fileId, fileData, callback)
{
    var request = gapi.client.request({
        'path': '/upload/drive/v2/files/' + fileId,
        'method': 'PUT',
        'params': { 'uploadType': 'media', 'alt': 'json' },
        'headers': { 'Content-Type': 'application/json' },
        'body': fileData
    });

    request.execute(function (a, b)
    {
        if ($.isFunction(callback))
            callback();
    });
}